import 'package:sqflite/sqflite.dart';
import '../database/database_helper.dart';
import '../models/forum_message.dart';

class ForumService {
  final dbHelper = DatabaseHelper.instance;

  Future<int> insertMessage(ForumMessage message) async {
    Database db = await dbHelper.database;
    return await db.insert('forum_messages', message.toMap());
  }

  Future<List<ForumMessage>> getAllMessages() async {
    Database db = await dbHelper.database;
    List<Map<String, dynamic>> maps = await db.query(
      'forum_messages',
      orderBy: 'publishDate DESC', // Show newest messages first
    );
    return List.generate(maps.length, (i) => ForumMessage.fromMap(maps[i]));
  }

  Future<int> deleteMessage(int id) async {
    Database db = await dbHelper.database;
    return await db.delete(
      'forum_messages',
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  Future<List<ForumMessage>> getMessagesByUserId(int userId) async {
    Database db = await dbHelper.database;
    List<Map<String, dynamic>> maps = await db.query(
      'forum_messages',
      where: 'userId = ?',
      whereArgs: [userId],
      orderBy: 'publishDate DESC',
    );
    return List.generate(maps.length, (i) => ForumMessage.fromMap(maps[i]));
  }
}
